var express = require('express');
var router = express.Router();
var {userModel,typeOneModel,typeTwoModel,BooksModel,historyModel,carlistModel} = require('../model/model');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get("/aaa",async(req,res)=>{
    let {data} = await userModel.find()
    console.log(data)
    res.send(data)
})

//获取数据
router.get("/getdatajjt",async(req,res)=>{
  let {page,pageSize,typeOneId,typeTwoId} = req.query
  let oneData = await typeOneModel.find()
  let twoData = await typeTwoModel.find().populate("typeOneId")
  let bookData = []
  if(page && pageSize){
    bookData = await BooksModel.find().populate("typeTwoId").populate("typeOneId").skip((page-1)*pageSize).limit(pageSize)
  }else{
    bookData = await BooksModel.find().populate("typeTwoId").populate("typeOneId")
  }
 if(typeOneId ){
  bookData = bookData.filter(item=>item.typeOneId._id == typeOneId)
 }
  res.send({
    oneData,
    twoData,
    bookData
  })
})
//获取历史记录数据
router.get("/hisdatajjt",async(req,res)=>{
  let {name} = req.query
  let newname = new RegExp(name)
  let ress = []
  if(name){
    ress = await BooksModel.find({name:newname})
  }else{
    ress = await BooksModel.find()
  }
  let data = await historyModel.find()
  let copy = data.reverse().slice(0,5)

  res.send({
    copy,
    ress
  })
})
//添加数据历史记录
router.post("/hisaddjjt",async(req,res)=>{
  let body = req.body
 await historyModel.create(body)
  res.send({
    code:200
  })
})
//获取user数据
router.get("/userdata",async(req,res)=>{
  let userData = await userModel.find().lean()
  let user = []
  let boodata = await BooksModel.find().lean()
  userData.forEach(item=>{
    // console.log(item)
    let arr = [item.lng,item.lat]
    user.push(arr)
  })
  let list = []
  userData.forEach(item=>{
    let suer1 = boodata.filter(ele=>ele.userId == item._id)
    let ele = item
    if( suer1.length>0){
      
     ele.bookimg= suer1.reverse()[0].image
     ele.bookname= suer1.reverse()[0].name
     list.push(ele)
    }else{
      ele.bookimg= ""
      ele.bookname= ""
      list.push(ele)
    }
  })
  let usermessage = []
  userData.forEach(item=>{
    let suer2 = boodata.filter(ele=>ele.userId == item._id)
    let ele = item
    if( suer2.length>0){
      
     ele.children= suer2
     usermessage.push(ele)
    }else{
      ele.children= []
      usermessage.push(ele)
    }
  })
  console.log(usermessage,1111)
  res.send({
    userData:list,//
    user ,  //用户位置信息
    usermessage
  })
})
//加入gouwuche 
router.post("/caradd", async(req, res) => {
  let _id = req.body._id
 
  let data = await carlistModel.find({ _id });
  if(data.length>0){
    res.send({
      code: 201,
      msg: "添加失败",
    })
  }else{
    await carlistModel.create(req.body);
    res.send({
      code: 200,
      msg: "添加成功",
    });
  }
  
});
module.exports = router;
